<template>
  <div >
      <el-dialog :title="isEdit ? '修改部门' : '新增部门'" :visible.sync="localFormVisible" :before-close="closeDialog" width="25%" :close-on-click-modal="false">
          <el-form :model="formData" :rules="rules" ref="formRef">
              <el-form-item v-if="isEdit" label="部门编号" :label-width="formLabelWidth" prop="deptId">
                  <el-input v-model="formData.deptId" autocomplete="off" readonly></el-input>
              </el-form-item>
              <el-form-item label="部门名称" :label-width="formLabelWidth" prop="deptName">
                  <el-input v-model="formData.deptName" autocomplete="off"></el-input>
              </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
              <el-button @click="closeDialog">关闭</el-button>
              <el-button type="primary" @click="saveForm">保存</el-button>
          </div>
      </el-dialog>
  </div>
</template>

<script>
export default {
    name: "DeptFrom",
    data(){
        return{
            //表单元素宽度
            formLabelWidth: '120px',
            localFormVisible: this.formVisible,
            rules: {
                deptName: [
                    { required: true, message: '部门名称不能为空', trigger: 'blur' },
                    { validator: this.validateDeptName, trigger: 'blur' }
                ]
            }
        }
    },
    methods: {
        closeDialog() {
            this.localFormVisible = false;
            //通知父组件修改formVisible的值为false
            this.$emit('update:formVisible', false)
        },
        //提交表单
        saveForm() {
            this.$refs['formRef'].validate((valid) => {
                if (valid) {
                    //调用父组件的保存方法
                    this.$emit('submitForm', this.formData)
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        //验证部门名称
        async validateDeptName(rule, value, callback) {
            if (!value) {
                return callback(new Error('部门名称不能为空'));
            }else {
                try {
                    if (this.isEdit) {
                        const originalDept = (await this.$http.post('/getDeptById/' + this.formData.deptId)).data
                        if (originalDept.deptName !== value) {
                            const response = await this.$http.post('/checkDeptName/' + value);
                            if (response.data) {
                                callback(new Error('部门已存在'));
                            } else {
                                callback();
                            }
                        }
                    } else {
                        const response = await this.$http.post('/checkDeptName/' + value);
                        if (response.data) {
                            callback(new Error('部门已存在'));
                        } else {
                            callback();
                        }
                    }
                }catch (error) {
                    console.error('验证时出错:', error);
                    callback(new Error('验证时出错，请稍后再试'));
                }
            }
        },
    },
    props: {
        isEdit: {
            type: Boolean,
            default: false
        },
        formVisible: {
            type: Boolean,
            default: false
        },
        formData: Object,
    },
    watch: {
        formVisible(newVal) {
            this.localFormVisible = newVal; // 当 `prop` 改变时，更新本地变量
            if (newVal) {
                if(this.$refs['formRef']) {
                    this.$refs['formRef'].resetFields(); // 当弹框打开时重置表单
                }
            }
        }
    }
}
</script>

<style scoped>

</style>